package com.xxl.job.admin.core.scheduler;

import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.thread.*;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.client.ExecutorBizClient;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author xuxueli 2018-10-28 00:18:17
 */

public class XxlJobScheduler  {
    private static final Logger logger = LoggerFactory.getLogger(XxlJobScheduler.class);


    /**
     * 初始化XXL-JOB管理端的核心组件。
     * <p>
     * 该方法按顺序执行以下初始化操作：
     * 1. 初始化国际化配置。
     * 2. 启动任务触发池。
     * 3. 启动注册监控。
     * 4. 启动失败监控。
     * 5. 启动完成监控（依赖任务触发池）。
     * 6. 启动日志报告。
     * 7. 启动调度器（依赖任务触发池）。
     * <p>
     * 最后记录初始化成功信息。
     * @throws Exception 可能抛出的异常类型
     */
    public void init() throws Exception {
        // init i18n 初始化国际化配置
        initI18n();

        // admin trigger pool start 启动任务触发池：初始化快速和慢速触发池
        JobTriggerPoolHelper.toStart();

        // admin registry monitor run 启动注册监控：初始化用于处理注册与移除操作的线程池
        JobRegistryHelper.getInstance().start();

        // admin fail-monitor run 启动失败监控：启动一个用于监控作业失败的守护线程
        JobFailMonitorHelper.getInstance().start();

        // admin lose-monitor run ( depend on JobTriggerPoolHelper ) 初始化回调线程池和监控线程，用于处理任务结果丢失的情况
        JobCompleteHelper.getInstance().start();

        // admin log report start 启动日志报告线程：刷新日志报告和清理过期日志
        JobLogReportHelper.getInstance().start();

        // 核心：start-schedule  ( depend on JobTriggerPoolHelper ) 启动调度器线程和时间轮线程，负责任务调度和触发执行
        JobScheduleHelper.getInstance().start();

        logger.info(">>>>>>>>> init xxl-job admin success.");
    }

    
    public void destroy() throws Exception {

        // stop-schedule
        JobScheduleHelper.getInstance().toStop();

        // admin log report stop
        JobLogReportHelper.getInstance().toStop();

        // admin lose-monitor stop
        JobCompleteHelper.getInstance().toStop();

        // admin fail-monitor stop
        JobFailMonitorHelper.getInstance().toStop();

        // admin registry stop
        JobRegistryHelper.getInstance().toStop();

        // admin trigger pool stop
        JobTriggerPoolHelper.toStop();

    }

    // ---------------------- I18n ----------------------

    private void initI18n(){
        for (ExecutorBlockStrategyEnum item:ExecutorBlockStrategyEnum.values()) {
            item.setTitle(I18nUtil.getString("jobconf_block_".concat(item.name())));
        }
    }

    // ---------------------- executor-client ----------------------
    private static ConcurrentMap<String, ExecutorBiz> executorBizRepository = new ConcurrentHashMap<String, ExecutorBiz>();
    public static ExecutorBiz getExecutorBiz(String address) throws Exception {
        // valid
        if (address==null || address.trim().length()==0) {
            return null;
        }

        // load-cache
        address = address.trim();
        ExecutorBiz executorBiz = executorBizRepository.get(address);
        if (executorBiz != null) {
            return executorBiz;
        }

        // set-cache
        executorBiz = new ExecutorBizClient(address,
                XxlJobAdminConfig.getAdminConfig().getAccessToken(),
                XxlJobAdminConfig.getAdminConfig().getTimeout());

        executorBizRepository.put(address, executorBiz);
        return executorBiz;
    }

}
